import swaggerJSDoc from 'swagger-jsdoc';
import { config } from '@/config';

/**
 * Swagger 配置选项
 */
const swaggerOptions: swaggerJSDoc.Options = {
  definition: {
    openapi: '3.0.0',
    info: {
      title: 'JMTemp Server API',
      version: config.app.version,
      description: '基于 Node.js 的后端 API 项目脚手架',
      contact: {
        name: 'API Support',
        email: 'support@example.com',
        url: 'https://example.com/support',
      },
      license: {
        name: 'MIT',
        url: 'https://opensource.org/licenses/MIT',
      },
    },
    servers: [
      {
        url: config.app.env === 'production' 
          ? 'https://api.example.com' 
          : `http://localhost:${config.app.port}`,
        description: config.app.env === 'production' ? '生产环境' : '开发环境',
      },
    ],
    components: {
      securitySchemes: {
        bearerAuth: {
          type: 'http',
          scheme: 'bearer',
          bearerFormat: 'JWT',
          description: 'JWT 认证令牌',
        },
      },
      schemas: {
        // 通用响应模式
        ApiResponse: {
          type: 'object',
          properties: {
            success: {
              type: 'boolean',
              description: '请求是否成功',
            },
            code: {
              type: 'integer',
              description: '状态码',
            },
            message: {
              type: 'string',
              description: '响应消息',
            },
            data: {
              description: '响应数据',
            },
            timestamp: {
              type: 'string',
              format: 'date-time',
              description: '响应时间',
            },
          },
        },
        // 分页响应模式
        PaginatedResponse: {
          allOf: [
            { $ref: '#/components/schemas/ApiResponse' },
            {
              type: 'object',
              properties: {
                pagination: {
                  type: 'object',
                  properties: {
                    page: {
                      type: 'integer',
                      description: '当前页码',
                    },
                    limit: {
                      type: 'integer',
                      description: '每页数量',
                    },
                    total: {
                      type: 'integer',
                      description: '总记录数',
                    },
                    totalPages: {
                      type: 'integer',
                      description: '总页数',
                    },
                  },
                },
              },
            },
          ],
        },
        // 错误响应模式
        ErrorResponse: {
          type: 'object',
          properties: {
            success: {
              type: 'boolean',
              example: false,
            },
            code: {
              type: 'integer',
              description: '错误状态码',
            },
            message: {
              type: 'string',
              description: '错误消息',
            },
            timestamp: {
              type: 'string',
              format: 'date-time',
            },
            path: {
              type: 'string',
              description: '请求路径',
            },
          },
        },
        // 用户模式
        User: {
          type: 'object',
          properties: {
            id: {
              type: 'string',
              description: '用户ID',
            },
            username: {
              type: 'string',
              description: '用户名',
              minLength: 3,
              maxLength: 20,
            },
            email: {
              type: 'string',
              format: 'email',
              description: '邮箱地址',
            },
            firstName: {
              type: 'string',
              description: '名字',
              maxLength: 50,
            },
            lastName: {
              type: 'string',
              description: '姓氏',
              maxLength: 50,
            },
            phone: {
              type: 'string',
              description: '手机号',
              pattern: '^1[3-9]\\d{9}$',
            },
            avatar: {
              type: 'string',
              format: 'uri',
              description: '头像URL',
            },
            bio: {
              type: 'string',
              description: '个人简介',
              maxLength: 500,
            },
            role: {
              type: 'string',
              enum: ['admin', 'user', 'moderator', 'guest'],
              description: '用户角色',
            },
            status: {
              type: 'string',
              enum: ['active', 'inactive', 'suspended', 'pending', 'deleted'],
              description: '用户状态',
            },
            emailVerified: {
              type: 'boolean',
              description: '邮箱是否已验证',
            },
            lastLoginAt: {
              type: 'string',
              format: 'date-time',
              description: '最后登录时间',
            },
            createdAt: {
              type: 'string',
              format: 'date-time',
              description: '创建时间',
            },
            updatedAt: {
              type: 'string',
              format: 'date-time',
              description: '更新时间',
            },
          },
        },
        // 用户注册请求
        UserRegisterRequest: {
          type: 'object',
          required: ['username', 'email', 'password', 'firstName', 'lastName'],
          properties: {
            username: {
              type: 'string',
              minLength: 3,
              maxLength: 20,
              pattern: '^[a-zA-Z0-9_]+$',
            },
            email: {
              type: 'string',
              format: 'email',
            },
            password: {
              type: 'string',
              minLength: 8,
              pattern: '^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*?&])[A-Za-z\\d@$!%*?&]{8,}$',
            },
            firstName: {
              type: 'string',
              minLength: 1,
              maxLength: 50,
            },
            lastName: {
              type: 'string',
              minLength: 1,
              maxLength: 50,
            },
            phone: {
              type: 'string',
              pattern: '^1[3-9]\\d{9}$',
            },
          },
        },
        // 用户登录请求
        UserLoginRequest: {
          type: 'object',
          required: ['email', 'password'],
          properties: {
            email: {
              type: 'string',
              format: 'email',
            },
            password: {
              type: 'string',
            },
            rememberMe: {
              type: 'boolean',
              default: false,
            },
          },
        },
        // 分页参数
        PaginationQuery: {
          type: 'object',
          properties: {
            page: {
              type: 'integer',
              minimum: 1,
              default: 1,
              description: '页码',
            },
            limit: {
              type: 'integer',
              minimum: 1,
              maximum: 100,
              default: 10,
              description: '每页数量',
            },
            sortBy: {
              type: 'string',
              default: 'createdAt',
              description: '排序字段',
            },
            sortOrder: {
              type: 'string',
              enum: ['asc', 'desc'],
              default: 'desc',
              description: '排序方向',
            },
            keyword: {
              type: 'string',
              description: '搜索关键词',
            },
          },
        },
      },
    },
    security: [
      {
        bearerAuth: [],
      },
    ],
    tags: [
      {
        name: 'Health',
        description: '健康检查相关接口',
      },
      {
        name: 'Auth',
        description: '认证相关接口',
      },
      {
        name: 'Users',
        description: '用户管理接口',
      },
    ],
  },
  apis: [
    './src/routes/*.ts',
    './src/controllers/*.ts',
    './docs/swagger/*.yaml',
  ],
};

/**
 * 生成 Swagger 规范
 */
export const swaggerSpec = swaggerJSDoc(swaggerOptions);

/**
 * Swagger UI 配置
 */
export const swaggerUiOptions = {
  customCss: `
    .swagger-ui .topbar { display: none }
    .swagger-ui .info { margin: 20px 0 }
    .swagger-ui .scheme-container { margin: 20px 0 }
  `,
  customSiteTitle: 'JMTemp Server API Documentation',
  swaggerOptions: {
    persistAuthorization: true,
    displayRequestDuration: true,
    filter: true,
    showExtensions: true,
    showCommonExtensions: true,
    defaultModelsExpandDepth: 2,
    defaultModelExpandDepth: 2,
  },
};

export default swaggerSpec;